﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;

namespace cn.Util
{
    /// <summary>
    /// 获取配置文件信息
    /// </summary>
    public class WebConfig
    {
        public static bool GetBool(string key)
        {
            return GetString(key).ToLower().Equals("True");
        }

        public static int GetInt(string key)
        {
            return Convert.ToInt32(GetString(key));
        }

        public static string GetString(string key)
        {
           return ConfigurationManager.AppSettings[key].ToString();
        }


        /// <summary>
        /// 当前是不是winform程序
        /// </summary>
        public static bool IsWinform
        {
            get
            {
                return System.Web.HttpContext.Current == null ? true : false;
            }
        }

        private static string _ConfigFilePath = string.Empty;

        /// <summary>
        /// 站点配置文件路径
        /// </summary>
        public static string ConfigFilePath
        {
            get
            {
                if (string.IsNullOrEmpty(_ConfigFilePath))
                {
                    string temp = System.Configuration.ConfigurationManager.AppSettings["ConfigPath"];

                    if (temp == null)
                    {
                        throw new Exception("配置文件ConfigPath不存在");
                    }

                    bool isWinform = System.Web.HttpContext.Current == null ? true : false;

                    _ConfigFilePath =isWinform ? Path.GetFullPath(temp):PathHelp(AppDomain.CurrentDomain.BaseDirectory, temp);
                }

                return _ConfigFilePath;
            }
        }


        /// <summary>
        /// 将path和相对路径合并 组成新的路径
        /// </summary>
        /// <param name="path"></param>
        /// <param name="relativelyPath"></param>
        /// <returns></returns>
        public static string PathHelp(string path, string relativelyPath)
        {
            if (relativelyPath.StartsWith(".\\") || relativelyPath.StartsWith("~/") || relativelyPath.StartsWith("./"))
            {
                if (path.LastIndexOf("/") == path.Length || path.LastIndexOf("\\") == path.Length-1)
                {
                    path = path.Substring(0, path.Length - 1);
                }

                if (path.IndexOf("/") != -1)
                {
                    path = path.Substring(0, path.LastIndexOf("/") );
                }
                else
                {
                    path = path.Substring(0, path.LastIndexOf("\\") );
                }
                return path + relativelyPath.Replace(".","");
            }
            else
            {
                return relativelyPath;
            }
        }


    }
}
